from flask import Blueprint,render_template,request,jsonify,make_response,redirect,g
import json
from models.user.User import User
from Service import UserService
from app import app,db

route_user = Blueprint('user_page',__name__ )

@route_user.route("/login",methods=["GET","POST"])
def login():
    if request.method == "GET":
        return render_template("user/login.html")

    resp = {'code':200,'msg':'登录成功！','data':{}}
    req_dic = request.values
    login_name = req_dic["login_name"]
    login_pwd = req_dic["login_pwd"]

    user = User.query.filter_by(login_name=login_name).first()
    if not user:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登录用户名!"
        return jsonify(resp)
    if user.login_pwd != UserService.genePwd(login_pwd,user.login_salt):
        resp['code'] = -1
        resp['msg'] = "请输入正确的密码!"
        return jsonify(resp)

    # 已删除，且他的身份不是主管理员
    if user.identity != 1 and user.status == 0:
        resp['code'] = -1
        resp['msg'] = "账号异常,请联系主管理员!"
        return jsonify(resp)

    response = make_response(json.dumps(resp))
    response.set_cookie(app.config["AUTH_COOKIE_NAME"],"%s#%s"%(UserService.geneAuthCode(user),user.uid), 60*60*24*30) #cookie保存30天
    return response


@route_user.route("/edit",methods=["GET","POST"])
def edit():
    current_user = g.current_user
    if request.method == "GET":
        return render_template("user/edit.html", current_user=current_user)

    req_dict = request.values
    current_user.nickname = req_dict["nickname"]
    if req_dict["sex"] == "男":
        current_user.sex = 1
    else:
        current_user.sex = 0
    current_user.mobile = req_dict["mobile"]
    current_user.email = req_dict["email"]
    try:
        db.session.add(current_user)
        db.session.commit()
    except:
        return jsonify({"code": -1, "msg": "提交失败！"})

    return jsonify({"code": 200, "msg": "提交成功！"})


@route_user.route("/reset-pwd",methods=["GET","POST"])
def resetPwd():
    current_user = g.current_user
    if request.method == "GET":
        return render_template("user/reset_pwd.html", current_user=current_user)

    req_dic = request.values
    old_pwd = UserService.genePwd(req_dic["old_password"],current_user.login_salt)
    if old_pwd != current_user.login_pwd:
        return jsonify({"code":-1,"msg":"旧密码错误！"})

    current_user.login_pwd = UserService.genePwd(req_dic["new_password"],current_user.login_salt)
    try:
        db.session.add(current_user)
        db.session.commit()
    except:
        return jsonify({"code": -1, "msg": "提交失败！"})

    return jsonify({"code": 200, "msg": "提交成功！"})


@route_user.route("login-out")
def loginOut():
    response = make_response(redirect("/user/login"))
    response.delete_cookie(app.config["AUTH_COOKIE_NAME"])
    return response

